package com.iguo.tube.util;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Service
public class FileDeletionScheduler {

  public static final String ANSI_RESET = "\u001B[0m";
  public static final String ANSI_BLUE = "\u001B[34m";


  @Value("${upload.cache}")
  String directoryPath;
  @Value("${upload.time}")
  Integer cacheTime;
  //删除缓存文件夹中过期的表格
  @Scheduled(fixedRate = 30000)
  public void fileDeletionScheduler() {
    List<String> fileNames = new ArrayList<>();
    // 要删除的文件路径
    File directory = new File(directoryPath);
    if (directory.isDirectory()) {
      // 列出目录中的文件
      File[] files = directory.listFiles();
      if (files != null) {
        LocalDateTime currentDateTime = LocalDateTime.now();
        LocalDateTime fiveMinutesBeforeNow = currentDateTime.minusMinutes(cacheTime);
        System.out.println("定时任务扫描目录中的文件:      "+ ANSI_BLUE + "当前时间: "+currentDateTime + ANSI_RESET);
        for (File file : files) {
          // 只打印文件名
          if (file.isFile()) {
            String dateString = file.getName();
            String datePart = dateString.split(" ")[0].replace("_", " ");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
            LocalDateTime parsedDate = LocalDateTime.parse(datePart, formatter);

            if (parsedDate.isBefore(fiveMinutesBeforeNow)) {
              System.err.println("文件" + dateString + "存储时间超时，已删除   ");
              fileNames.add(file.getName());
            }
          }
        }
      } else {
        System.out.println("目录为空或无法访问。");
      }
    } else {
      System.out.println(directoryPath + " 不是一个有效的目录路径。");
    }
    for (String fileName : fileNames) {
      File fileToDelete = new File(directoryPath + "\\" + fileName);
      if (fileToDelete.exists()) {
        fileToDelete.delete();
      } else {
        System.out.println("文件不存在: " + fileToDelete);
      }
    }
  }
}
